<?php

namespace app\controller;

use app\BaseController;
use app\service\UserService;
use think\facade\Config;
use think\facade\Env;
use think\facade\Request;

class User extends BaseController
{
    public function index()
    {
//        $carsdatas=$this->request->param('carsdata');
//        $carsdata=json_decode($carsdatas,true);
//        foreach ($carsdata as $k=>$v){
//            echo  $v['name'];
//        }
//        echo   GetRandInt(20);
        $data = [
            'uid' => 1,
            'timestamp' => '1647307444',
            'nonce' => 'BY7EGHGzi3tFul0l',
        ];
        $api_salt = 'F6Z7z5POhE';
        sort($data, SORT_STRING);
        $paramsRes = implode($data);
        // key进行排序
        $signRes = md5($paramsRes . $api_salt);
        echo $signRes;
        $res = [
            ['id' => 1, 'start_time' => '2021-1-1', 'end_time' => '2021-1-1'],
            ['id' => 2, 'start_time' => '2021-1-1', 'end_time' => '2021-1-1'],
            ['start_time' => '2021-1-1', 'end_time' => '2021-1-1']
        ];
        echo json_encode($res);
    }

    public function hello($name = 'ThinkPHP6')
    {
        return 'hello,' . $name;
    }

    public function logout()
    {
        $uid = Request::param('uid/d', 0);
        $res = UserService::logout($uid);
        if ($res) {
            returnSuccess(200, '退出成功');
        } else {
            returnFail(20019, '退出失败');
        }
    }

    //上传图片
    public function uploadimg()
    {
        $param['uid'] = Request::param('uid/d', '');
        $param['img'] = Request::param('img/s', '');
        if ($param['img'] == '') {
            returnFail(21076, '请传入内容');
        }
        $reg = '/^(data:\s*image\/(\w+);base64,)/';
        if (!preg_match($reg, $param['img'], $result)) {
            returnFail(21076, '图片格式不正确');
        }
        $rootPath =  Env::get('rootPath','/www/wwwroot/pre_erp_tms_app.dtveek.com');
//        $up_dir=app()->getRootPath()."/public/upload/".date('ymd');
        $up_dir = $rootPath . "/public/upload/" . date('ymd') . "/";
        if (!file_exists($up_dir)) {
            mkdir($up_dir,0777,true);
        }
        $type = $result[2];
        if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
            $filename = md5(date('YmdHis') . mt_rand(1, 1000)) . '.' . $type;
            $new_file = $up_dir . $filename;
            // echo $new_file;die();
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $param['img'])))) {
                $api_host = Config::get('app.api_host');
                returnSuccess(200, '上传成功', ['img_url' => $api_host . date('ymd') . "/" . $filename]);
            } else {
                returnFail(21077, '上传失败');
            }
        } else {
            returnFail(21076, '图片格式不正确');
        }
    }
}
